// pages/setBudget/setBudget.js
const db = wx.cloud.database()
const _ = db.command
Page({
  data: {

  },

  budgetSubmit: function(e) {
    console.log(e.detail.value)
    wx.cloud.callFunction({
      name: 'update_budget',
      data: {
        openid: this.data.openid,
        budget: e.detail.value.budget
      },
      success: res => {
        var newBudget = e.detail.value.budget
        var pages = getCurrentPages();
        var prevPage = pages[pages.length - 2];
        this.setData({
          budget: newBudget
        })
        prevPage.setData({
          budget: newBudget
        })
        console.log(res)
        wx.showToast({
          title: '预算修改成功！',
        })
      }
    })
  },

  onLoad: function (options) {
    wx.setNavigationBarTitle({
      title: '修改预算',
    })
    this.setData({
      openid: options.openid,
      totalMonth: options.totalMonth,
      totalToday: options.totalToday
    })
    db.collection("user_budget").where({_openid: this.data.openid}).get()
    .then(res => {
      console.log(res)
      if (res.data.length == 0) {
        this.setData({
          budget: 0
        })
      }
      else {
        this.setData({
          budget: res.data[0].budget
        })
      }
      console.log("budget="+budget)
    })
    .catch(err => {
      console.log(err)
    })
  },
})